package com.yuanqi.controller;

import com.yuanqi.domain.RetailProduct;
import com.yuanqi.domain.ProductStatus;
import com.yuanqi.service.RetailProductService;
import com.yuanqi.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.HashMap;

/**
 * 零售商品控制器
 */
@RestController
@RequestMapping("/api/retail/products")
@CrossOrigin(origins = "*")
public class RetailProductController {
    
    @Autowired
    private RetailProductService retailProductService;
    
    @Autowired
    private FileUploadService fileUploadService;
    
    /**
     * 创建零售商品
     */
    @PostMapping
    public ResponseEntity<RetailProduct> createProduct(@RequestBody RetailProduct product) {
        try {
            RetailProduct createdProduct = retailProductService.createRetailProduct(product);
            return ResponseEntity.ok(createdProduct);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 更新零售商品
     */
    @PutMapping("/{id}")
    public ResponseEntity<RetailProduct> updateProduct(@PathVariable Long id, @RequestBody RetailProduct product) {
        try {
            product.setId(id);
            RetailProduct updatedProduct = retailProductService.updateRetailProduct(product);
            return ResponseEntity.ok(updatedProduct);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 根据ID查找零售商品
     */
    @GetMapping("/{id}")
    public ResponseEntity<RetailProduct> getProduct(@PathVariable Long id) {
        Optional<RetailProduct> product = retailProductService.findById(id);
        return product.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 根据商品ID查找零售商品
     */
    @GetMapping("/by-product-id/{productId}")
    public ResponseEntity<RetailProduct> getProductByProductId(@PathVariable Long productId) {
        Optional<RetailProduct> product = retailProductService.findByProductId(productId);
        return product.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }
    
    
    /**
     * 分页查找零售商品
     */
    @GetMapping
    public ResponseEntity<Page<RetailProduct>> getProducts(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<RetailProduct> products = retailProductService.findAll(pageable);
        return ResponseEntity.ok(products);
    }
    
    /**
     * 根据状态查找零售商品
     */
    @GetMapping("/by-status/{status}")
    public ResponseEntity<List<RetailProduct>> getProductsByStatus(@PathVariable String status) {
        ProductStatus productStatus = ProductStatus.valueOf(status);
        List<RetailProduct> products = retailProductService.findByStatus(productStatus);
        return ResponseEntity.ok(products);
    }
    
    /**
     * 根据商品ID查询
     */
    @GetMapping("/search")
    public ResponseEntity<List<RetailProduct>> searchProducts(@RequestParam Long productId) {
        List<RetailProduct> products = retailProductService.findByProductIdAndStatus(productId);
        return ResponseEntity.ok(products);
    }
    
    /**
     * 查找低库存商品
     */
    @GetMapping("/low-stock")
    public ResponseEntity<List<RetailProduct>> getLowStockProducts() {
        List<RetailProduct> products = retailProductService.findLowStockProducts();
        return ResponseEntity.ok(products);
    }
    
    /**
     * 查找缺货商品
     */
    @GetMapping("/out-of-stock")
    public ResponseEntity<List<RetailProduct>> getOutOfStockProducts() {
        List<RetailProduct> products = retailProductService.findOutOfStockProducts();
        return ResponseEntity.ok(products);
    }
    
    /**
     * 调整商品库存
     */
    @PostMapping("/{productId}/adjust-stock")
    public ResponseEntity<RetailProduct> adjustStock(
            @PathVariable Long productId,
            @RequestParam Integer quantity,
            @RequestParam String reason,
            @RequestParam(defaultValue = "系统") String operatorName) {
        try {
            RetailProduct product = retailProductService.adjustStock(productId, quantity, reason, operatorName);
            return ResponseEntity.ok(product);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 更新商品状态
     */
    @PutMapping("/{productId}/status")
    public ResponseEntity<RetailProduct> updateStatus(
            @PathVariable Long productId,
            @RequestParam String status) {
        try {
            ProductStatus productStatus = ProductStatus.valueOf(status);
            RetailProduct product = retailProductService.updateStatus(productId, productStatus);
            return ResponseEntity.ok(product);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 批量更新商品状态
     */
    @PutMapping("/batch-status")
    public ResponseEntity<Void> batchUpdateStatus(
            @RequestBody List<Long> productIds,
            @RequestParam String status) {
        try {
            ProductStatus productStatus = ProductStatus.valueOf(status);
            retailProductService.batchUpdateStatus(productIds, productStatus);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 删除零售商品
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
        try {
            retailProductService.deleteById(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 获取商品统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Object> getProductStatistics() {
        Object statistics = retailProductService.getProductStatistics();
        return ResponseEntity.ok(statistics);
    }
    
    /**
     * 获取商品销售统计
     */
    @GetMapping("/{productId}/sales-stats")
    public ResponseEntity<Object> getProductSalesStats(@PathVariable Long productId) {
        try {
            Object salesStats = retailProductService.getProductSalesStats(productId);
            return ResponseEntity.ok(salesStats);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 获取商品库存变动记录
     */
    @GetMapping("/{productId}/inventory-history")
    public ResponseEntity<Object> getProductInventoryHistory(@PathVariable Long productId) {
        try {
            Object inventoryHistory = retailProductService.getProductInventoryHistory(productId);
            return ResponseEntity.ok(inventoryHistory);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 上传商品图片到MinIO
     */
    @PostMapping("/upload-image/{productId}")
    public ResponseEntity<?> uploadProductImage(@PathVariable Long productId, @RequestParam("file") MultipartFile file) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "请选择要上传的文件");
                return ResponseEntity.badRequest().body(error);
            }
            
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "只支持图片文件");
                return ResponseEntity.badRequest().body(error);
            }
            
            // 验证文件大小 (5MB)
            if (file.getSize() > 5 * 1024 * 1024) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "文件大小不能超过5MB");
                return ResponseEntity.badRequest().body(error);
            }
            
            // 上传文件到MinIO
            String fileName = fileUploadService.uploadProductImage(file, productId);
            String fileUrl = fileUploadService.getFileUrl(fileName);
            
            // 更新商品图片URL
            retailProductService.updateProductImageUrl(productId, fileUrl);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "商品图片上传成功");
            response.put("fileName", fileName);
            response.put("fileUrl", fileUrl);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "商品图片上传失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
}
